import {formatRichText} from '../../../utils/utils.js'

const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isShowTop:false,
    toView:'works-detail',
    winHeight: '100%',
    anchorArray:null,
    selectFloorIndex:0,
    menuList:[
      {
        name:'商品',
        id:'works-detail',
      },
      {
        name:'详情',
        id:'works-describe'
      },
      {
        name:'评价',
        id:'works-evaluation'
      }
    ],
    evaluationTypeIndex:0,
    id:'',
    worksDetail:'',
    desc:'',
    worksCommentList:'',
    pageNum:1,
    nextPage: '',
    type:'',
    shopCollectType:'0',
    userOrderGoodsDetail:'',
    btnFunName:'',
    btnText:'',
    buyShow:false,
    evaluationLoad:false,
    evaluationLoadBool:false,
    fileShow:false,
    attachment:[],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      id: options.id,
      type: options.type
    })
    if (options.type == 1){
      wx.setNavigationBarTitle({
        title: '作品详情'
      })
    }else{
      wx.setNavigationBarTitle({
        title: '服务详情'
      })
    }
    // 详情
    this.worksDetail();
    // 评论
    this.worksComment();
  },

  fileClose(){
    this.setData({
      fileShow: false
    })
  },

  goShop(e){
    let { id,uid,shop_status } = e.currentTarget.dataset;
    let shopType = 1;
    if(shop_status != 1){
      id = uid,
      shopType = 2
    }
    wx.navigateTo({
      url: '/taskPage/pages/talentDetail/talentDetail?id=' + id + '&shopType=' + shopType,
    })
  },


  optionHand(){
    const {worksDetail,id}=this.data
    if(worksDetail.cash==='0.00'){

     /* wx.navigateTo({
        url: '/taskPage/pages/worksDown/worksDown?id='+id,
      })*/
      this.setData({
        fileShow:true
      })

      return
    }
    if(this.data.btnFunName){
      this[this.data.btnFunName]()
    }
  },

  collection(){
    if(this.data.shopCollectType){
      this.delCollectBtn()
    }else {
      this.collectBtn()
    }
  },

  /**
   * 锚点
   * @param event
   */
  selectKm(event){
    let data=event.currentTarget.dataset.id
    this.setData({
      toView: data
    })
  },

  /**
   * 获取页面高度
   */
  getWinHeight(){
    let that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          winHeight: res.windowHeight
        })
      }
    });
  },

  getScrollHeight(){
    let query = wx.createSelectorQuery().in(this);
    let heightArr =[];
    let h = 0;
    query.selectAll('.floorType').boundingClientRect((react)=>{
      react.forEach((res)=>{
        h+=res.height;
        heightArr.push(h)
      })
      this.setData({
        anchorArray:heightArr
      });
    }).exec();
  },


  /**
   * 判断导航显示
   * @param e
   */
  handelScroll(e){
    let scrollTop=e.detail.scrollTop;
    if(scrollTop>20){
      this.setData({
        isShowTop:true
      })
    }else{
      this.setData({
        isShowTop:false
      })
    }
    let scrollArr= this.data.anchorArray;
    if(scrollTop>=scrollArr[scrollArr.length-1]-this.data.autoHeight){
      return;
    }else {
      for(let i=0;i<scrollArr.length;i++){
        if(scrollTop>=0&&scrollTop<scrollArr[0]){
          // selectFloorIndex控制筛选块高亮显示
          this.setData({
            selectFloorIndex: 0
          });
        }else if(scrollTop>=scrollArr[i-1]&&scrollTop<scrollArr[i]) {
          this.setData({
            selectFloorIndex: i
          });
        }
      }
    }
  },



  rateChange(){

  },
  // 评级类别
  evaluationTypeBtn: function (e) {
    var { index } = e.target.dataset
    this.setData({
      evaluationTypeIndex: index,
      nextPage:'',
      worksCommentList:'',
      pageNum:1
    })
    this.worksComment();
  },
  // 详情
  worksDetail:function(){
    var _this = this;
    var {id} = this.data
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: app.globalData.baseUrl + 'shop/goodsDetail',
      data: {
        goods_id: id,
        token: app.globalData.token
      },
      success(res) {
        wx.hideLoading()
        if (res.data.code == 1000) {
          if(res.data.data.goodsDetail.uid!==wx.getStorageSync('uid')){
            _this.setData({
              buyShow:true
            })
          }
          let desc=res.data.data.goodsDetail.desc
          desc=formatRichText(desc)
          _this.setData({
            desc,
            worksDetail: res.data.data.goodsDetail,
            userOrderGoodsDetail: res.data.data.userOrderGoodsDetail,
            attachment:res.data.data.userOrderGoodsDetail.attachment
          })
          _this.btnChange(res.data.data)
          _this.shopCollectType();
        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },


  btnChange(data){
    let {type,worksDetail}=this.data

    if(worksDetail.cash==='0.00'){
      this.setData({
        btnText:"下载",
      })
      return
    }
    if(type==2){
      this.setData({
        btnText:"雇佣TA",
        btnFunName:'hireBtn',
      })
    }else {
      if(!data.userOrderGoodsDetail.isBuy){
        this.setData({
          btnText:"立即购买",
          btnFunName:'buyWorks',
        })
      }
      if(data.userOrderGoodsDetail.isBuy && !data.userOrderGoodsDetail.isRights){
        this.setData({
          btnText:"下载源文件",
          btnFunName:'wxdown',
        })
      }
      if(data.userOrderGoodsDetail.isBuy && data.userOrderGoodsDetail.isRights){
        this.setData({
          btnText:"维权中",
        })
      }
    }
  },



  // 评论
  worksComment:function(){
    this.setData({
      evaluationLoadBool:true,
      evaluationLoad:true,
    })
    var _this = this;
    var type;
    var { id, evaluationTypeIndex, pageNum, nextPage, worksCommentList } = this.data
    if (nextPage == null){
      wx.showToast({
        title: '暂无更多评论！',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    if (evaluationTypeIndex == 0){
      type = 'all'
    }else{
      type = evaluationTypeIndex
    }

    wx.request({
      url: app.globalData.baseUrl + 'shop/getGoodsComments',
      data: {
        goods_id: id,
        type: type,
        page: pageNum
      },
      success(res) {
        _this.setData({
          evaluationLoadBool:false,
          evaluationLoad:false,
        })
        if (res.data.code == 1000) {
          _this.setData({
            worksCommentList: [...worksCommentList, ...res.data.data.goodsComments.data],
            nextPage: res.data.data.goodsComments.next_page_url
          })
        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  // 联系
  contactBtn: function () {
    var { worksDetail } = this.data;
    //if (worksDetail.shop.user.mobile == null){
      wx.showToast({
        title: '请前往pc端im工具联系服务商',
        icon: 'none',
        duration: 2000
      })
      return false
   // }
    /*wx.makePhoneCall({
      phoneNumber: worksDetail.shop.user.mobile
    })*/
  },
  // 立即购买
  buyWorks:function(){
    var { worksDetail } = this.data
    var url = app.globalData.baseUrl + 'user/buyGoods';
    var data = {
      goods_id: worksDetail.id,
      token: app.globalData.token
    }
    if (!app.globalData.token){
      wx.showModal({
        title: '提示',
        content: '您未登录，是否去登陆？',
        success(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/userPage/pages/login/login',
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      return false
    }
    wx.showLoading({
      title: '正在生成订单',
    })
    app.wxGetRequest(url, data, (res) => {
      wx.hideLoading()
      if (res.code == 1000) {
        wx.navigateTo({
          url: '/taskPage/pages/worksPay/worksPay?title=' + worksDetail.title + '&cash=' + worksDetail.cash + '&orderid=' + res.data.order_id + '&code=' + res.data.code,
        })
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none',
          duration: 2000
        })
      }
    }, (err) => {
      wx.hideLoading()
    })
  },
  // 雇佣
  hireBtn:function(){
    if (!app.globalData.token) {
      wx.showModal({
        title: '提示',
        content: '您未登录，是否去登陆？',
        success(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/userPage/pages/login/login',
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      return false
    }
    var { worksDetail } = this.data
    wx.navigateTo({
      url: '/pages/hireForm/hireForm?userName=' + worksDetail.shop.user.name + '&uid=' + worksDetail.uid + '&id=' + worksDetail.id + '&type=2',
    })
  },
  // 店铺收藏状态
  shopCollectType:function(){
    var { worksDetail } = this.data
    var _this = this
    var url = app.globalData.baseUrl + 'shop/collectStatus';
    var data = {
      shop_id: worksDetail.shop.id,
      token: app.globalData.token
    }
    wx.showLoading({
      title: '加载中',
    })
    app.wxGetRequest(url, data, (res) => {
      wx.hideLoading()
      if (res.code == 1000) {
        _this.setData({
          shopCollectType: res.data.status
        })
      }
    }, (err) => {
      wx.hideLoading()
      wx.showToast({
        title: err.data.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  // 收藏店铺
  collectBtn:function(){
    var _this = this
    var url = app.globalData.baseUrl + 'shop/collect';
    var { worksDetail } = this.data
    if (!app.globalData.token){
      wx.showModal({
        title: '提示',
        content: '您未登录，是否去登陆？',
        success(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/userPage/pages/login/login',
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      return false
    }
    var data = {
      shop_id: worksDetail.shop.id,
      token: app.globalData.token
    }
    wx.showLoading({
      title: '加载中',
    })
    app.wxPostRequest(url, data, (res) => {
      wx.hideLoading()
      if (res.code == 1000) {
        wx.showToast({
          title: '收藏成功',
          icon: 'success',
          duration: 1500
        })
        setTimeout(function(){
          _this.shopCollectType()
        },1500)
      }
    }, (err) => {
      wx.hideLoading()
      wx.showToast({
        title: err.data.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  // 取消收藏
  delCollectBtn:function(){
    var _this = this
    var url = app.globalData.baseUrl + 'shop/cancelCollect';
    var { worksDetail } = this.data
    var data = {
      shop_id: worksDetail.shop.id,
      token: app.globalData.token
    }
    wx.showLoading({
      title: '加载中',
    })
    app.wxPostRequest(url, data, (res) => {
      wx.hideLoading()
      if (res.code == 1000) {
        wx.showToast({
          title: '取消成功',
          icon: 'success',
          duration: 1500
        })
        setTimeout(function () {
          _this.shopCollectType()
        }, 1500)
      }
    }, (err) => {
      wx.hideLoading()
      wx.showToast({
        title: err.data.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  // 下载源文件
  wxdown:function(){
    var { userOrderGoodsDetail } = this.data
    wx.navigateTo({
      url: '/taskPage/pages/worksConfirm/worksConfirm?order_id=' + userOrderGoodsDetail.order_id,
    })
  },



  // 附件下载
  fileDown: function (event) {
    let  { down_url, annextype } = event.currentTarget.dataset;
    let _that = this;
    if (annextype != 'jpg' && annextype != 'png' && annextype != 'jpeg' && annextype != 'gif') {
      if (annextype != 'zip' && annextype != 'rar') {
        wx.downloadFile({
          url: down_url,
          success: function (res) {
            const tempFilePath = res.tempFilePath;
            // 保存文件
            wx.saveFile({
              tempFilePath,
              success: function (res) {
                const savedFilePath = res.savedFilePath;
                // 打开文件
                wx.openDocument({
                  filePath: savedFilePath,
                  showMenu:true,
                  success: function (res) {
                    console.log('打开文档成功')
                  },
                });
              },
              fail: function (err) {
                console.log('保存失败：', err)
              }
            });
          },
          fail: function (err) {
            console.log('下载失败：', err);
          },
        });
      } else {
        wx.showToast({
          title: '暂不支持改文件类型',
          icon: "none",
          duration: 2000
        })
      }
      return false;
    } else {
      wx.showToast({
        icon: 'loading',
        title: '正在保存图片',
        duration: 1000
      })
      //判断用户是否授权"保存到相册"
      wx.getSetting({
        success(res) {
          //没有权限，发起授权
          if (!res.authSetting['scope.writePhotosAlbum']) {
            wx.authorize({
              scope: 'scope.writePhotosAlbum',
              success() {//用户允许授权，保存图片到相册
                _that.savePhoto(down_url);
              },
              fail() {//用户点击拒绝授权，跳转到设置页，引导用户授权
                wx.openSetting({
                  success() {
                    wx.authorize({
                      scope: 'scope.writePhotosAlbum',
                      success() {
                        _that.savePhoto(down_url);
                      }
                    })
                  }
                })
              }
            })
          } else {//用户已授权，保存到相册
            _that.savePhoto(down_url);
          }
        }
      })
    }
  },
  //保存图片到相册，提示保存成功
  savePhoto(down_url) {
    wx.downloadFile({
      url: down_url,
      success: function (res) {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success(res) {
            wx.showToast({
              title: '保存成功',
              icon: "success",
              duration: 1000
            })
          }
        })
      }
    })
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
      this.getWinHeight()
    this.getScrollHeight()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var { pageNum } = this.data;
    pageNum ++;
    this.setData({
      pageNum
    })
    this.worksComment();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
